home *** CD-ROM | disk | FTP | other *** search
/ Pascal Super Library / Pascal Super Library (CW International)(1997).bin / LIBRARY / PCTV3N3 / BINTOH.C < prev    next >
Text File  |  1992-05-29  |  2KB  |  67 lines

  1. /*
  2.   Program:                bin_to_h
  3.  
  4.   Author:                 Dr. Michael Milligan
  5.  
  6.   Description:    This program will read a file in binary mode
  7.                   and create a C header file containing the
  8.                   binary data.
  9.  
  10.  
  11.   To use:
  12.  
  13.   bin_to_h source dest
  14.  
  15.   where source is the name of a binary file to be
  16.   converted, dest is the name of the header file created.
  17.  
  18. */
  19.  
  20. #include <stdio.h>
  21.  
  22. #define LINE_1 "\t unsigned char bin_data[] = {"
  23. #define LINE_LAST "\n\t};\n"
  24. #define BUFSIZE 512
  25. #define CRLF "\r\n"
  26.  
  27. void fatal( char * );
  28.  
  29. void main(int argc, char* argv[] )
  30. {
  31.         FILE *fin, *fout;
  32.         char buf[BUFSIZE], *ch, xch;
  33.         int i, nbytes, col=0;
  34.         long totbytes = 0;
  35.  
  36.         if (argc != 3) fatal( "bin_to_h source dest\n");
  37.  
  38.         if ( !(fin  = fopen( argv[1], "rb" ) ) )
  39.                 fatal( "Error opening input file.\n") ;
  40.         if ( !(fout = fopen( argv[2], "wb" ) ) )
  41.                 fatal( "Error opening output file.\n");
  42.  
  43.         fprintf( fout, LINE_1 );
  44.         printf("bin_to_h converting...\n");
  45.  
  46.         while ( nbytes = fread( buf, 1, BUFSIZE, fin ) ) {
  47.           for (i=0; i < nbytes; i++ ) {
  48.                totbytes++;
  49.                if ( !(col++ % 6))
  50.                     fprintf( fout, CRLF "\t\t");
  51.                fprintf( fout, "\'\\x" );
  52.                fprintf( fout, "%02x", (unsigned char) buf[i] );
  53.                fprintf( fout, "\', " );
  54.             }
  55.         }
  56.         fprintf( fout, LINE_LAST );
  57.         fclose( fin );
  58.         fclose( fout );
  59.         printf("\nTotal bytes processed: %ld\n", totbytes);
  60. }
  61.  
  62. void fatal( char * error)
  63. {
  64.         fprintf( stderr, "%s", error );
  65.         exit( 1 );
  66. }
  67.